package com.mcxx.util;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;


public class HttpServiceUtil {

    private static final Logger logger = LoggerFactory.getLogger(HttpServiceUtil.class);

    public static String callService(String biz_content,Map<String,String> header,String url ,String accessKey,String version) {


        String access_key = accessKey;

        String format = "json";

        String request_id = UUID.randomUUID().toString().replaceAll("-", "").substring(0, 20);

        String timestamp = String.valueOf(System.currentTimeMillis());
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("access_key", access_key);
        paramMap.put("biz_content", biz_content);
        paramMap.put("format", format);
        paramMap.put("request_id", request_id);
        paramMap.put("version", version);
        paramMap.put("timestamp", timestamp);
        paramMap.put("mock", "");
        String source = EsbUtil.generateSignSource(paramMap);


        String sign = null;
        try {
            sign = EsbUtil.sign(source, "consumer_private.keystore");
        } catch (Exception e) {
            logger.error("签名失败");
            logger.error(e.getMessage(),e);
            return "签名失败";
        }
        paramMap.put("sign",sign);
        String res = OkHttpUtil.doPostWithHeader(url, paramMap, header, "");


        return res;
    }


    public static void callServiceWithFile(String serviceKey, String accessKey,String url,File file, String param) {
        try {

            String access_key = accessKey;

            String request_id = UUID.randomUUID().toString().replaceAll("-",
                    "").substring(0, 20);

            String timestamp = String.valueOf(System.currentTimeMillis());
            Map<String, String> paramMap = new HashMap<>();
            paramMap.put("access_key", access_key);
            paramMap.put("request_id", request_id);
            paramMap.put("timestamp", timestamp);
            String source = EsbUtil.generateSignSource(paramMap);

            String sign = EsbUtil.sign(source, "consumer_private.keystore");
            HttpPost post = new HttpPost(url+serviceKey);
//            HttpPost post = new HttpPost("http://10.72.0.52:10050/engine/transport/"+serviceKey);
//          HttpPost post = new HttpPost("http://10.72.0.131:9010/support/cardIdentificationRestService/bankCardIdentification");
            post.setHeader("access_key", access_key);
            post.setHeader("sign", sign);
            post.setHeader("timestamp", timestamp);
            post.setHeader("request_id", request_id);
            CloseableHttpClient httpClient = HttpClientBuilder.create().build();
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();

            builder.addBinaryBody("imgFile", file, ContentType.MULTIPART_FORM_DATA, file.getName());
            builder.addTextBody("detectPhoto",param);
            HttpEntity entity = builder.build();
            post.setEntity(entity);
            HttpResponse response = httpClient.execute(post);

            int statusCode = response.getStatusLine().getStatusCode();
            logger.info("statusCode:" + statusCode);
            logger.info("response:" +
                    EntityUtils.toString(response.getEntity()));
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
        }
    }

    public static String callServiceWithFileByOkHttp(String serviceKey,String accessKey,String url,File file, Map<String,String> param) {
        try {

            String request_id = UUID.randomUUID().toString().replaceAll("-",
                    "").substring(0, 20);

            String timestamp = String.valueOf(System.currentTimeMillis());
            Map<String, String> header = new HashMap<>();
            header.put("access_key", accessKey);
            header.put("request_id", request_id);
            header.put("timestamp", timestamp);
            String source = EsbUtil.generateSignSource(header);

            String sign = EsbUtil.sign(source, "consumer_private.keystore");
            header.put("sign",sign);
            return OkHttpUtil.doPostWithFile(url+serviceKey,header,param,file);
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
        }
        return "";
    }


    public static String callServiceWithNativeHttp(String access_key, String address,Map<String, String> param,String version) {

        String biz_content = JSONObject.toJSONString(param);

        String format = "json";

        String request_id = UUID.randomUUID().toString().replaceAll("-", "").substring(0, 20);

        String timestamp = String.valueOf(System.currentTimeMillis());

        String mock = "";
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("biz_content", biz_content);
        paramMap.put("access_key", access_key);
        paramMap.put("version", version);
        paramMap.put("format", format);
        paramMap.put("request_id", request_id);
        paramMap.put("timestamp", timestamp);
        paramMap.put("mock", mock);
        String source = EsbUtil.generateSignSource(paramMap);


        String sign = null;
        try {
//            sign = EsbUtil.sign(source, "consumer_private_RSA.keystore");
            sign = EsbUtil.sign(source, "consumer_private.keystore");
        } catch (Exception e) {
            logger.error("签名失败");
            logger.error(e.getMessage(),e);
            return "";
        }

        sign = sign.replaceAll("[+]", "%2B");

        String paramStr = source + "&sign=" + sign;
        logger.info(paramStr);
        OutputStreamWriter out = null;
        BufferedReader in = null;
        try {
            URL url = new URL(address);
            URLConnection conn = url.openConnection();
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            //post传参
            conn.setDoOutput(true);
            conn.setDoInput(true);
            out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
            out.write(paramStr);
            out.flush();
            in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            StringBuilder resultBuilder = new StringBuilder();
            while ((line = in.readLine()) != null) {
                resultBuilder.append(line);
            }
            //结果输出
            logger.info("res:"+resultBuilder.toString());
            return resultBuilder.toString();
        } catch (IOException e){
            logger.error(e.getMessage(),e);
        }
        return null;
    }

    /**
     * 原生http调用服务集成管理平台接口
     * 核对同步方法调用网关接口
     * @param access_key 调用标识
     * @param address 调用地址
     * @param biz_content 入参
     * @param version 版本号
     * @throws Exception
     */
    public static String callServiceWithNativeHttp(String access_key, String address,String biz_content,String version) {

        String format = "json";

        String request_id = UUID.randomUUID().toString().replaceAll("-", "").substring(0, 20);

        String timestamp = String.valueOf(System.currentTimeMillis());

        String mock = "";
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("biz_content", biz_content);
        paramMap.put("access_key", access_key);
        paramMap.put("version", version);
        paramMap.put("format", format);
        paramMap.put("request_id", request_id);
        paramMap.put("timestamp", timestamp);
        paramMap.put("mock", mock);
        String source = EsbUtil.generateSignSource(paramMap);


        String sign = null;
        try {
//            sign = EsbUtil.sign(source, "consumer_private_RSA.keystore");
            sign = EsbUtil.sign(source, "consumer_private.keystore");
        } catch (Exception e) {
            logger.error("签名失败");
            logger.error(e.getMessage(),e);
            return "";
        }

        sign = sign.replaceAll("[+]", "%2B");

        String paramStr = source + "&sign=" + sign;
        logger.info(paramStr);
        OutputStreamWriter out = null;
        BufferedReader in = null;
        try {
            URL url = new URL(address);
            URLConnection conn = url.openConnection();
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            //post传参
            conn.setDoOutput(true);
            conn.setDoInput(true);
            out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
            out.write(paramStr);
            out.flush();
            in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            StringBuilder resultBuilder = new StringBuilder();
            while ((line = in.readLine()) != null) {
                resultBuilder.append(line);
            }
            //结果输出
            logger.info("res:"+resultBuilder.toString());
            return resultBuilder.toString();
        } catch (IOException e){
            logger.error(e.getMessage(),e);
        }
        return null;
    }

    /**
     * 同步删除发放系统名册
     * @param fundPayId
     * @return
     */
    public static String httpCallDelFundpayData(String fundpayDelUrl, String fundPayId) {
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("fundPayId", fundPayId);
        String retBody = OkHttpUtil.doPost(fundpayDelUrl, fundPayId);
        logger.info("同步删除发放系统名册结果：{}", retBody);
        if(StringUtils.isNotEmpty(retBody)) {
            if(retBody.startsWith("Failed to connect to")) {
                return retBody;
            }
            try {
                JSONObject json = JSONObject.parseObject(retBody);
                String code = json.getString("code");
                String desc = json.getString("desc");
                if (!"1".equals(code)) {
                    return desc;
                }
            }catch(Exception e) {
                logger.error(e.getMessage(), e);
                return retBody;
            }
        }
        return null;
    }
}
